package websocket.controller;

/**
 * @ClassName CkgnjcController
 * @Des TODO
 * @Author lg
 * @Date 2022/6/23 17:22
 * @Version 1.0.0
 **/

import gnu.io.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import websocket.dto.ResultDTO;
import websocket.dto.ResultEnum;
import websocket.entity.Ckgnjc;
import websocket.entity.dto.CkgnjcDTO;
import websocket.entity.vo.SerialPortVo;
import websocket.service.CkgnjcService;
import websocket.util.SerialUtil;

/**
 * @ClassName LdmzjzController
 * @Des TODO 串口功能检测
 * @Author lg
 * @Date 2022/6/22 13:00
 * @Version 1.0.0
 **/
@RestController
@RequestMapping("/api/ckgnjc")
public class CkgnjcController {

    @Autowired
    private CkgnjcService ckgnjcService;

    /**
     * 保存数据
     *
     * @return
     */
    @PostMapping("/save")
    @ApiOperation("保存数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ckgnjc", value = "计算结果数据", required = true, dataType = "Ckgnjc", paramType = "body")
    })
    public ResultDTO save(@RequestBody Ckgnjc ckgnjc) {
        ckgnjcService.save(ckgnjc);
        return ResultDTO.success(null);
    }

    /**
     * 串口连接调试
     * 串口打开后需要进行串口数据监听---现在未实现
     *
     * @return
     */
    @GetMapping("/connect")
    @ApiOperation("串口连接调试")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ckmc", value = "串口名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "btl", value = "波特率", required = true, dataType = "String", paramType = "query")
    })
    public ResultDTO connect(@RequestParam(value = "ckmc") String ckmc,
                             @RequestParam(value = "btl") String btl) {

        try {
            // 通过端口名识别端口
            CommPortIdentifier portIdentifier = CommPortIdentifier
                    .getPortIdentifier(ckmc);
            // 打开端口，并给端口名字和一个timeout（打开操作的超时时间）
            CommPort commPort = portIdentifier.open(ckmc, 2000);

            // 判断是不是串口
            if (commPort instanceof SerialPort) {

                SerialPort serialPort = (SerialPort) commPort;
                SerialPortVo serialPortVo = new SerialPortVo(serialPort);
                serialPortVo.setName("转台串口");
                try {
                    // 设置一下串口的波特率等参数
                    serialPort.setSerialPortParams(Integer.valueOf(btl),
                            SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);
                } catch (UnsupportedCommOperationException e) {
                    return ResultDTO.fail(ResultEnum.FAIL_SERIAL);
                }
                return ResultDTO.success(null);

            } else {
                // 不是串口
                return ResultDTO.fail(ResultEnum.ERROR_SERIAL);
            }
        } catch (NoSuchPortException e1) {
            return ResultDTO.fail(ResultEnum.NOT_FIND_SERIAL);
        } catch (PortInUseException e2) {
            return ResultDTO.success(null);
        }
    }

    /**
     * 串口启动转台
     *
     * @return
     */
    @PostMapping("/start/{id}")
    @ApiOperation("启动")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "工作模式", required = true, dataType = "char", paramType = "path"),
            @ApiImplicitParam(name = "ckgnjcDTO", value = "串口名称", required = true, dataType = "CkgnjcDTO", paramType = "body")
    })
    public ResultDTO start(@PathVariable("id") char id,@RequestBody CkgnjcDTO ckgnjcDTO) {
        try {
            /**
             * 此处是串口连接调试
             */
            SerialUtil.sendDataToSerial(id, ckgnjcDTO, true);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultDTO.externalError(502, ex.getMessage());
        }
        return ResultDTO.success(null);
    }

    /**
     * 停止
     *
     * @return
     */
    @PostMapping("/stop")
    @ApiOperation("停止")
    public ResultDTO stop(@RequestBody CkgnjcDTO ckgnjcDTO) {

        try {

            // 通过端口名识别端口
            CommPortIdentifier portIdentifier = CommPortIdentifier
                    .getPortIdentifier(ckgnjcDTO.getCkh());
            // 打开端口，并给端口名字和一个timeout（打开操作的超时时间）
            CommPort commPort = portIdentifier.open(ckgnjcDTO.getCkh(), 2000);
            // 判断是不是串口
            if (commPort instanceof SerialPort) {

                SerialPort serialPort = (SerialPort) commPort;
                SerialPortVo serialPortVo = new SerialPortVo(serialPort);
                serialPortVo.setName("转台串口");
                serialPortVo.closePort();
                return ResultDTO.success(null);

            } else {
                // 不是串口
                return ResultDTO.fail(ResultEnum.ERROR_SERIAL);
            }
        } catch (NoSuchPortException e1) {
            return ResultDTO.fail(ResultEnum.NOT_FIND_SERIAL);
        } catch (PortInUseException e2) {
            return ResultDTO.success(null);
        }
    }
}
